package czy.demo.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 内存用户认证配置
 */
//@EnableWebSecurity
//@EnableGlobalAuthentication
//@EnableGlobalMethodSecurity(prePostEnabled = true,jsr250Enabled = true,securedEnabled = true)
public class InMemoryAuthConfig extends WebSecurityConfigurerAdapter {

    /* 加密 */
    private PasswordEncoder encoder = new BCryptPasswordEncoder();

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 配置了两个内存用户，只有三个字段：用户名、密码、角色
         * 其中角色为字符串数组
         * 目前的5.0版本中密码必须要进行加密：
         * 1.存储密码时就需要加密好
         * 2.设置加密方式，以便后面的密码比较
         */
         auth.inMemoryAuthentication()
         .withUser("zhangsan").password(encoder.encode("123456")).roles("ADMIN","USER")
         .and()
         .withUser("lisi").password(encoder.encode("12345678")).roles("USER")
         .and()
         .passwordEncoder(encoder);

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/permit/all/**").permitAll()
                .antMatchers("/deny/all").denyAll()
                .antMatchers("/anonymous/**").anonymous()
                .antMatchers("/authenticated/**").authenticated()
                .antMatchers("/any/**").hasAnyRole("USER","ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/ip/**").hasIpAddress("192.168.1.174")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }
}
